package org.example.rocketmq.msg_type.affairs;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

/**
 * 创建事务监听器
 */
public class TransactionListenerImpl implements TransactionListener {
    /**
     * 执行本地事务
     *
     * @param message
     * @param o
     * @return
     */
    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        String tags = message.getTags();
        if (StringUtils.contains("TagA", tags)) {
            return LocalTransactionState.COMMIT_MESSAGE; // 提交
        }
        if (StringUtils.contains("TagB", tags)) {
            return LocalTransactionState.ROLLBACK_MESSAGE; // 回滚
        }

        return LocalTransactionState.UNKNOW; // 无状态
    }

    /**
     * 回查本地事务
     *
     * @param messageExt
     * @return
     */
    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        String tags = messageExt.getTags();
        if (StringUtils.contains("TagC", tags)) {
            return LocalTransactionState.COMMIT_MESSAGE; // 提交
        }
        if (StringUtils.contains("TagD", tags)) {
            return LocalTransactionState.ROLLBACK_MESSAGE; // 回滚
        }

        return LocalTransactionState.UNKNOW; // 无状态
    }
}
